package oss

import (
	"fmt"
	"log"

	"go-learn/go_learn/prometheus/web_hook/global"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gogf/gf/os/gtime"
)

func (o *ossClient) ClearOss(ossPath string) {
	bucket, _ := o.client.Bucket(o.config.Bucket)
	prefix := oss.Prefix(getClearOssPath(ossPath))
	quantum := 0
	for {
		list, _ := bucket.ListObjectsV2(prefix)
		objectKeys := []string{}

		for _, v := range list.Objects {
			objectKeys = append(objectKeys, v.Key)
		}
		if len(objectKeys) <= 0 {
			break
		}
		result, err := bucket.DeleteObjects(objectKeys)
		if err != nil {
			log.Println(err)
		}
		quantum += len(objectKeys)
		log.Println(result)
	}
	fmt.Println("clear quantum：", quantum)
}

func getClearOssPath(date string) string {
	// return global.Prometheus.StoragePath + gtime.Now().AddDate(0, 0, -1).Format("Y-m-d")
	return global.Prometheus.StoragePath + date
}

func (o *ossClient) ClearOssByDate(clearDays int) {
	for i := 1; i < clearDays; i++ {
		addDays := 0 - i
		date := gtime.Now().AddDate(0, 0, addDays).Format("Y-m-d")
		ossPath := getClearOssPath(date)
		o.ClearOss(ossPath)
	}
}
